<template>
    <el-dialog ref="dialogform" :title="addEditName + title" :visible.sync="dialogVisible" width="90%"
        :before-close="handleClose">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
            <el-row v-show="addEditFlag !== 'lookView'" :gutter="20">
                <el-col :span="12">
                    <el-form-item label="路线名称" prop="routeName">
                        <el-input v-model="ruleForm.routeName" class="w100p" clearable placeholder="请输入路线名称"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="选择点位">
                        <el-select v-model="routePointId" class="w100p" clearable filterable placeholder="请选择点位"
                            @change="handleChoosePoint">
                            <el-option :disabled="pointIdList.indexOf(item.pointId) !== -1"
                                v-for="item, index in pointList" :key="index" :label="item.pointName"
                                :value="item.pointId"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <div class="pointList">
                <span class="label">点位列表</span>
                <div class="tagList">
                    <el-tag size="medium" class="elTag" v-if="ruleForm.pointList"
                        v-for="point, index in ruleForm.pointList" :key="index" :closable="addEditFlag!=='lookView'" :disable-transitions="false"
                        @click="centerAndZoom({ lng: point.longitude, lat: point.latitude })"
                        @close="handleCloseTag(index)">
                        {{ point.pointName }}：{{ `${point.longitude},${point.latitude}` }}
                    </el-tag>
                </div>
                <span class="warningText" v-show="!ruleForm.pointList || !ruleForm.pointList.length">请选择点位</span>
            </div>
            <div class="w100p mapContent" v-loading="mapLoading">
                <baidu-map :center="mapCenter" :zoom="mapZoom" :scroll-wheel-zoom="true" map-type="BMAP_HYBRID_MAP"
                    @click="handleMapClick" style="height: 100%; width: 100%;" @ready="handler">
                    <bm-marker v-for="(marker, index) in polylinePath" :key="index"
                        :position="{ lng: marker.lng, lat: marker.lat }">
                        <bm-label :content="marker.info.pointName" :label-style="labelStyle"
                            :offset="{ width: -15, height: 30 }" />
                    </bm-marker>
                    <bm-local-search :keyword="keyword" :auto-viewport="true" :panel="false" />
                    <bm-polyline stroke-style="dashed" stroke-color="#6ecae3" :stroke-opacity="1" :stroke-weight="4"
                        :path="polylinePath" />
                    <bm-control>
                        <bm-auto-complete v-model="keyword" :sug-style="{ zIndex: 999999 }">
                            <el-input v-model="keyword" type="text" placeholder="请输入地名关键字"
                                style="width: 300px;margin: 10px;" clearable>
                                <i slot="prefix" class="el-input__icon el-icon-search"></i>
                            </el-input>
                        </bm-auto-complete>
                    </bm-control>
                </baidu-map>
            </div>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submitForm" v-show="addEditFlag !== 'lookView'">确 定</el-button>
        </span>
    </el-dialog>
</template>
<script>
import mapPath from '@/api/basic-info-manage/map-path';
export default {
    components: {},
    props: {
        addEditFlag: {
            type: String,
            default: () => {
                return 'add'
            }
        },
        data: {
            type: Object,
            default: () => {
                return {}
            }
        },
        title: {
            type: String,
            default: () => {
                return '操作表单'
            }
        },
        dialogVisible: {
            type: Boolean,
            default: () => {
                return false
            }
        },
        pointList: {
            type: Array,
            default: () => {
                return []
            }
        },
    },
    data() {
        return {
            routePointId: '',
            mapLoading: false,
            map: null,
            baiduMap: null,
            keyword: '',
            locations: {},
            mapCenter: { lng: 116.404, lat: 39.915 }, // 设置地图中心点坐标（经度，纬度）  
            mapZoom: 19, // 设置地图缩放级别  
            markers: [],// 用于存放地图上的标记点，
            addEditName: '添加',
            addEditApi: '',
            ruleForm: {},
            pointIdList: [],
            polylinePath: [],
            maxLong: 1000,
            labelStyle: {
                color: "#fffff0",
                fontSize: "12px",
                borderRadius: "8px",
                border: "none",
                backgroundColor: "#00a1c2",
                padding: "3px 15px",
                opacity: ".8"
            },
            rules: {
                routeName: [
                    { required: true, message: '请输入路线名称', trigger: 'change' }
                ],
                routePointIdList: [
                    { required: true, message: '请选择点位', trigger: 'change' }
                ],
            }
        }
    },
    watch: {
        dialogVisible(v) {
            v && this.initData()
        }
    },

    mounted() { },
    methods: {
        initData() {
            if (this.addEditFlag == 'add') {
                this.resetForm();
                this.addEditApi = mapPath.add;
                this.addEditName = '添加';
                this.markers = [];
                this.geolocation();
                this.$set(this.ruleForm, 'errorRange', 50);
            } else if (this.addEditFlag == 'edit') {
                this.ruleForm = { ...this.data }
                this.addEditApi = mapPath.edit
                this.addEditName = '编辑';
                this.mapLoading = true;
                setTimeout(() => {
                    this.mapLoading = false;
                    this.handleLatLng();
                }, 1500)
            } else if (this.addEditFlag == 'lookView') {
                this.ruleForm = { ...this.data }
                this.addEditApi = mapPath.edit
                this.addEditName = '查看';
                this.mapLoading = true;
                setTimeout(() => {
                    this.mapLoading = false;
                    this.handleLatLng();
                }, 1500)
            }
        },
        handleCloseTag(index) {
            this.pointIdList.splice(index, 1);
            this.getPointList(this.pointIdList);
        },
        handleChoosePoint(id) {
            let indexOfNum = this.pointIdList.indexOf(id);
            let length = this.ruleForm.pointList?.length;
            if (this.pointIdList.length > 0) {
                let rut1 = this.pointList.find(item => {
                    return item.pointId == id
                });
                let rut2 = this.ruleForm.pointList[length - 1];
                let distance = this.getDistance(rut1.latitude, rut1.longitude, rut2.latitude, rut2.longitude);
                console.log(distance)
                if (distance > this.maxLong) {
                    this.$confirm('您选择的点位距离上个点位超出' + this.maxLong + '米，您确定继续选择该点位吗?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        if (indexOfNum !== -1) {
                            this.pointIdList.splice(indexOfNum, 1)
                        } else {
                            this.pointIdList.push(id)
                        }
                        this.getPointList(this.pointIdList);
                    })
                } else {
                    if (indexOfNum !== -1) {
                        this.pointIdList.splice(indexOfNum, 1)
                    } else {
                        this.pointIdList.push(id)
                    }
                    this.getPointList(this.pointIdList);
                }
            } else {
                this.pointIdList.push(id)
                this.getPointList(this.pointIdList);
            }

        },

        getPointList(idList) {
            let pointList = [];
            this.markers = [];
            this.polylinePath = [];
            idList.forEach((id, index) => {
                let rut = this.pointList.find(item => {
                    return item.pointId == id
                });
                let marker = { lat: Number(rut.latitude), lng: Number(rut.longitude) }
                //添加marker点
                this.markers.push({
                    position: { ...marker }
                });
                //定位到最后一个添加的点位位置
                if (index + 1 == idList.length) {
                    this.centerAndZoom(marker);
                };
                pointList.push(rut);
            });
            this.polylinePath = pointList.map(item => {
                return {
                    lat: item.latitude,
                    lng: item.longitude,
                    info: item
                }
            })
            this.$set(this.ruleForm, 'pointList', pointList);
        },
        getDistance(lat1, lon1, lat2, lon2) {
            var R = 6371e3; // 地球半径，单位为米  
            var phi1 = lat1 * Math.PI / 180; // 将纬度转换为弧度  
            var phi2 = lat2 * Math.PI / 180;
            var deltaPhi = (lat2 - lat1) * Math.PI / 180;
            var deltaLambda = (lon2 - lon1) * Math.PI / 180;

            var a = Math.sin(deltaPhi / 2) * Math.sin(deltaPhi / 2) +
                Math.cos(phi1) * Math.cos(phi2) *
                Math.sin(deltaLambda / 2) * Math.sin(deltaLambda / 2);
            var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

            var distance = R * c; // 计算结果即为两点之间的距离，单位为米  
            console.log(distance)
            return distance;
        },
        handler({ BMap, map }) {
            this.map = map;
            this.baiduMap = BMap;
            if (this.addEditFlag == 'add') {
                this.geolocation();
            }
        },
        geolocation() {
            if (!this.baiduMap) return;
            const geolocation = new this.baiduMap.Geolocation()
            geolocation.getCurrentPosition((res) => {
                this.locations.lng = res.point.lng;
                this.locations.lat = res.point.lat;
                console.log(this.locations)
                this.$set(this.ruleForm, 'longitude', res.point.lng);
                this.$set(this.ruleForm, 'latitude', res.point.lat);
                // this.markers = [{ position: { ...res.point } }];
                this.centerAndZoom(res.point)
            })
        },
        handleLatLng() {
            this.pointIdList = [];
            this.polylinePath = [];
            this.pointIdList = this.ruleForm.pointList.map(point => {
                return point.pointId
            });

            this.getPointList(this.pointIdList);
        },
        centerAndZoom(marker) {
            if (marker.lng && marker.lat) {
                let point = new this.baiduMap.Point(marker.lng, marker.lat)
                this.map.centerAndZoom(point, 19);
            }
        },
        handleMapClick(e) {
            const { lng, lat } = e.point; // 获取点击的经纬度  
            this.markers = [{ position: { lng, lat } }];// 将点击的坐标添加到标记点数组中  
            this.$set(this.ruleForm, 'longitude', lng);
            this.$set(this.ruleForm, 'latitude', lat);
        },
        //提交表单
        submitForm() {
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    this.addEditApi({ ...this.ruleForm, routePointMapperList: this.ruleForm.pointList || [] }).then(res => {
                        let msg = res.success ? '操作成功' : '操作失败'
                        this.$message[res.success ? 'success' : 'warning'](res.msg || msg)
                        res.success && this.cancel();
                    }).catch(err => {
                        console.log(err)
                    })
                } else {
                    return false;
                }
            })
        },
        //重置
        resetForm() {
            this.pointIdList = [];
            this.ruleForm = {};
            this.$refs.ruleForm && this.$refs.ruleForm.resetFields()
        },
        //取消关闭
        cancel() {
            this.resetForm()
            this.$emit("closeDialog")
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => { this.resetForm(); this.cancel() })
                .catch(_ => { });
        }
    }
};
</script>
<style lang="scss" scoped>
.mapContent {
    width: 100%;
    height: 650px;
}

::v-deep .el-dialog {
    margin-top: 30px !important;
}

.pointList {
    width: 100%;
    padding-left: 10px;
    min-height: 40px;
    display: flex;
    justify-content: flex-start;
    flex-wrap: nowrap;

    .label {
        width: 98px;
        font-weight: bold;
        margin-right: 15px;
        line-height: 28px;
        text-align: right;
    }

    .elTag {
        margin-bottom: 5px;
        margin-right: 5px;
        cursor: pointer;
    }

    .tagList {
        display: flex;
        justify-content: flex-start;
        flex-wrap: wrap;
    }
}
</style>